package com.mida.dms.knw.service.impl;

import com.mida.dms.knw.entity.DtDefineSpace;
import com.mida.dms.knw.entity.DtDefineSpaceConsumer;
import com.mida.dms.knw.entity.vo.DtDefineSpaceConsumerVo;
import com.mida.dms.knw.entity.vo.DtDefineSpaceVo;
import com.mida.dms.knw.mapper.DtDefineSpaceConsumerMapper;
import com.mida.dms.knw.mapper.DtDefineSpaceMapper;
import com.mida.dms.knw.mapper.KnwNoumenonMapper;

import com.mida.dms.knw.service.DtDefineSpaceService;
import com.mida.dms.knw.service.SoidService;
import com.mida.dms.knw.util.CharTransFormUtil;
import com.mida.dms.knw.util.DataSetConstants;
import com.mida.dms.knw.vo.Page;
import com.mida.dms.knw.vo.PageResultVo;
import com.mida.tool.common.result.ActionResult;
import com.mida.tool.common.result.ListResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.StopWatch;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static com.mida.dms.knw.Result.BaseResult.*;

/**
 * @author ：wang xiao le
 * @description：TODO
 * @date ：2021/3/22 16:34
 */
@Service
@Slf4j
@Transactional(value = "dtdTxManager", rollbackFor = Exception.class)
public class DtDefineSpaceServiceIml implements DtDefineSpaceService {


    @Autowired
    private DtDefineSpaceMapper dtDefineSpaceMapper;

    @Autowired
    private DtDefineSpaceConsumerMapper dtDefineSpaceConsumerMapper;

    @Autowired
    private KnwNoumenonMapper knwNoumenonMapper;

    @Autowired
    private SoidService soidService;


    /**
     * 1、添加定义空间
     *
     * @param dtDefineSpaceVo
     * @return
     */
    @Override
    public ActionResult add(DtDefineSpaceVo dtDefineSpaceVo) {
        if (dtDefineSpaceVo.getDefineSpaceSoid() != null) {
            log.info(dtDefineSpaceVo.toString() + "不是一个新增，转到update去");
            return update(dtDefineSpaceVo);
        }
        log.info("开始添加定义空间" + dtDefineSpaceVo.toString());
        StopWatch st = StopWatch.createStarted();
        ActionResult ar = new ActionResult();
        try {
            if (StringUtils.isEmpty(dtDefineSpaceVo.getDefineSpaceName())) {
                ar.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
                ar.setMessage("定义空间名称不能为空");
                return ar;
            }
            int count = dtDefineSpaceMapper.countDefineSpaceName(dtDefineSpaceVo.getDefineSpaceName());
            if (count > 0) {
                ar.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
                ar.setMessage("定义空间名称已存在");
                return ar;
            }
            DtDefineSpace dtDefineSpace = new DtDefineSpace();
            BeanUtils.copyProperties(dtDefineSpaceVo, dtDefineSpace);
            dtDefineSpace.setPyCode(CharTransFormUtil.toPinyinSimple(dtDefineSpaceVo.getDefineSpaceName()));
            dtDefineSpace.setWbCode(CharTransFormUtil.toWubi(dtDefineSpaceVo.getDefineSpaceName()));
//            Long seq = oIDGanerator.getSOID();
            Long seq = soidService.getSoid();
            dtDefineSpace.setDefineSpaceSoid(seq);
            dtDefineSpace.setCreateDate(new Date());
            dtDefineSpace.setUpdateDate(new Date());
            dtDefineSpaceMapper.insert(dtDefineSpace);  //添加定义空间基本数据
            soidService.insertOid(seq,1);
//            String oid = oIDGanerator.getOID(0);
//            DtOid dtOid = new DtOid();
//            dtOid.setOid(oid);
//            dtOid.setSoid(seq);
//            dtOidMapper.insert(dtOid);
            //添加定义空间用户数据
            insertDefineSpaceCounsumer(dtDefineSpaceVo, dtDefineSpace);
            buildActionSuccess(ar);
        } catch (Exception e) {
            log.error("添加定义空间异常", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            buildActionWarn(ar, "添加定义空间失败");
        } finally {
            st.stop();
            log.info("本次新增耗时:" + st.getTime() + "ms");
        }
        return ar;
    }

    @Override
    public ActionResult update(DtDefineSpaceVo dtDefineSpaceVo) {

        log.info("开始更新定义空间" + dtDefineSpaceVo.toString());
        StopWatch st = StopWatch.createStarted();
        ActionResult ar = new ActionResult();
        try {
            if (dtDefineSpaceVo.getDefineSpaceSoid() == null) {

                throw new RuntimeException("定义空间soid不能为空");
            }
            if (StringUtils.isEmpty(dtDefineSpaceVo.getDefineSpaceName())) {
                ar.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
                ar.setMessage("定义空间名称不能为空");
                return ar;
            }
            int count = dtDefineSpaceMapper.countDefineSpaceName(dtDefineSpaceVo.getDefineSpaceName());
            DtDefineSpace dtDefineSpace = dtDefineSpaceMapper.selectByPrimaryKey(dtDefineSpaceVo.getDefineSpaceSoid());
            if (count > 0 && !dtDefineSpace.getDefineSpaceName().equals(dtDefineSpaceVo.getDefineSpaceName())) {
                ar.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
                ar.setMessage("定义空间名称已存在");
                return ar;
            }
            boolean equals = dtDefineSpace.equals(dtDefineSpaceVo);
            System.out.println("equals = " + equals);
            //1、校验定义空间基本信息是否修改
            if (!StringUtils.isEmpty(dtDefineSpaceVo) && !dtDefineSpace.equals(dtDefineSpaceVo)) {
                //1、1更新定义空间基本数据
                dtDefineSpace.setDefineSpaceName(dtDefineSpaceVo.getDefineSpaceName());
                dtDefineSpace.setHospitalSoid(dtDefineSpaceVo.getHospitalSoid());
                dtDefineSpace.setExamServiceType(dtDefineSpaceVo.getExamServiceType());
                dtDefineSpace.setPyCode(CharTransFormUtil.toPinyinSimple(dtDefineSpaceVo.getDefineSpaceName()));
                dtDefineSpace.setWbCode(CharTransFormUtil.toWubi(dtDefineSpaceVo.getDefineSpaceName()));
                dtDefineSpace.setUpdateDate(new Date());
                dtDefineSpaceMapper.updateByPrimaryKeySelective(dtDefineSpace);  //更新定义空间基本数据
            }
            //2、校验是否修改定义空间业务单元数据
            List<DtDefineSpaceConsumer> sourceConsumer = dtDefineSpaceConsumerMapper.findDefineSpaceSoid(dtDefineSpaceVo.getDefineSpaceSoid());
            List<DtDefineSpaceConsumerVo> targetConsumer = dtDefineSpaceVo.getDtDefineSpaceConsumerList();
            if (!targetConsumer.isEmpty()) {//目标定义空间不为空
                if (!sourceConsumer.isEmpty()) {//源定义空间不为空
                    if (!sourceConsumer.equals(targetConsumer)) { //定义空间有修改
                        //1、先删除
                        dtDefineSpaceConsumerMapper.deleteByDefineSpaceSoid(dtDefineSpace.getDefineSpaceSoid());
                        //2、添加定义空间业务单元数据
                        insertDefineSpaceCounsumer(dtDefineSpaceVo, dtDefineSpace);
                    }
                } else {//源定义空间为空，直接插入
                    insertDefineSpaceCounsumer(dtDefineSpaceVo, dtDefineSpace);
                }
            } else {//传入的定义空间为空，删除源定义空间
                dtDefineSpaceConsumerMapper.deleteByDefineSpaceSoid(dtDefineSpace.getDefineSpaceSoid());
            }

            buildActionSuccess(ar);
        } catch (Exception e) {
            log.error("更新定义空间异常", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            buildActionWarn(ar, "更新定义空间失败");

        } finally {
            st.stop();
            log.info("本次新增耗时:" + st.getTime() + "ms");
        }
        return ar;
    }

    /**
     * 3、删除定义空间
     *
     * @param defineSpaceSoid 定义空间soid
     * @return null
     */
    @Override
    public ActionResult delete(long defineSpaceSoid) {

        log.info("开始删除定义空间" + defineSpaceSoid);
        StopWatch st = StopWatch.createStarted();
        ActionResult ar = new ActionResult();
        try {
            //删除定义空间
            dtDefineSpaceMapper.deleteByPrimaryKey(defineSpaceSoid);
            //删除定义空间用户信息
            dtDefineSpaceConsumerMapper.deleteByDefineSpaceSoid(defineSpaceSoid);
            buildActionSuccess(ar);
        } catch (Exception e) {
            log.error("删除定义空间发送异常", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            buildActionWarn(ar, "删除定义空间失败");
        } finally {
            st.stop();
            log.info("本次删除耗时:" + st.getTime() + "ms");
        }
        return ar;
    }

    /**
     * 4、获取单个定义空间
     *
     * @param defineSpaceSoid 定义空间soid
     * @return
     */
    @Override
    public ListResult<DtDefineSpaceVo> get(long defineSpaceSoid) {
        log.info("开始获取单个定义空间" + defineSpaceSoid);
        StopWatch st = StopWatch.createStarted();
        ListResult<DtDefineSpaceVo> lr = new ListResult<DtDefineSpaceVo>();
        //获取定义空间
        try {
            DtDefineSpaceVo dtDefineSpaceVo = dtDefineSpaceMapper.selectByDefineSpaceSoid(defineSpaceSoid);
            buildListSuccess(lr,dtDefineSpaceVo);
        } catch (Exception e) {
            buildListWarn(lr,e);
        }
        return lr;
    }

    /**
     * 分页查询定义空间
     *
     * @param searChData  搜索关键字
     * @param currentPage 第几页
     * @param pageSize    每页显示数
     * @return
     */
    @Override
    public ListResult<PageResultVo<DtDefineSpaceVo>> findPage(String searChData, Long currentPage, Long pageSize) {
        log.info("开始分页查询,查询条件:" + searChData);
        ListResult result = new ListResult();
        PageResultVo pvo = new PageResultVo();
        Page page = new Page(currentPage, pageSize);
        pvo.setPage(page);
        StopWatch st = StopWatch.createStarted();
        List<DtDefineSpaceVo> list = null;
        try {

            Long pageSt = (currentPage - 1) * pageSize + 1;
            Long pageEd = currentPage * pageSize;
            if (searChData != null) {
                searChData = searChData.trim().toUpperCase();
            }
//            String search = searChData.toUpperCase();
            int count = Integer.valueOf(dtDefineSpaceMapper.findPageCount(pageSt, pageEd, searChData));
            if (count != 0) {
                page.setTotalCount(count);
                list = dtDefineSpaceMapper.findPage(pageSt, pageEd, searChData);
            } else {
                pvo.setPage(null);
            }
            pvo.setList(list);
            buildListSuccess(result, pvo);
        } catch (Exception e) {
            list = new ArrayList<DtDefineSpaceVo>(0);
            pvo.setList(list);
            log.error("分页查命名体系发送异常", e);
            buildListWarn(result, "分页查命名体系发送异常");
        } finally {
            st.stop();
            log.info("本次分页查询耗时:" + st.getTime() + "ms");

        }
        return result;
    }

    /**
     * 更改定义空间状态
     *
     * @param defineSpaceSoid 定义空间soid
     * @param status          状态soid
     * @return
     */
    @Override
    public ActionResult updateStatus(Long status, Long defineSpaceSoid) {
        log.info("开始定义空间状态" + status);
        StopWatch st = StopWatch.createStarted();
        ActionResult ar = new ActionResult();
        try {
            if (status == null) {
                throw new RuntimeException("定义空间状态不能为空");
            }
            if (defineSpaceSoid == null) {
                throw new RuntimeException("定义空间soid不能为空");
            }
            Integer defineSpaceSum = knwNoumenonMapper.countDefineSpace(defineSpaceSoid);
            if (defineSpaceSum != 0 && DataSetConstants.CLOSESTATUS.equals(status)) {
                ar.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
                ar.setMessage("定义空间已被引用，不能停用");
                return ar;
            }
            //1、更新定义空间状态
            DtDefineSpace dtDefineSpace = new DtDefineSpace();
            dtDefineSpace.setDefineSpaceSoid(defineSpaceSoid);
            dtDefineSpace.setStatus(status);
            dtDefineSpace.setUpdateDate(new Date());
            dtDefineSpaceMapper.updateByPrimaryKeySelective(dtDefineSpace);
            //2、更新定义用户信息状态
            dtDefineSpaceConsumerMapper.updateStatusByDefineSpaceSoid(status, defineSpaceSoid);
            buildActionSuccess(ar);
        } catch (Exception e) {
            log.error("更新定义空间状态异常", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            buildActionWarn(ar, "更新定义空间状态失败");
        } finally {
            st.stop();
            log.info("本次检查耗时:" + st.getTime() + "ms");
        }
        return ar;
    }


    /**
     * 定义空间名称重复性校验
     */
    @Override
    public ActionResult checkName(String name, Long defineSpaceSoid) {
        log.info("开始检查是否重名" + name);
        StopWatch st = StopWatch.createStarted();
        ActionResult ar = new ActionResult();
        try {
            if (StringUtils.isEmpty(name)) {
                ar.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
                ar.setMessage("定义空间名称不能为空");
                return ar;
            }

            int count = dtDefineSpaceMapper.countDefineSpaceName(name);
            if (count > 0 && defineSpaceSoid == null) {
                ar.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
                ar.setMessage("定义空间名称已存在");
                return ar;
            }
            if (defineSpaceSoid != null) {
                DtDefineSpace dtDefineSpace = dtDefineSpaceMapper.selectByPrimaryKey(defineSpaceSoid);
                if (count > 0 && !name.equals(dtDefineSpace.getDefineSpaceName())) {
                    ar.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
                    ar.setMessage("定义空间名称已存在");
                    return ar;
                }
            }
            buildActionSuccess(ar);
        } catch (Exception e) {
            log.error("检查是否重名异常", e);
            buildActionWarn(ar, "检查是否重名异常");
        } finally {
            st.stop();
            log.info("本次检查耗时:" + st.getTime() + "ms");
        }
        return ar;
    }


    /**
     * 8、查询所有定义空间
     *
     * @param searchData 搜索关键字
     * @return
     */
    @Override
    public ListResult<List<DtDefineSpace>> findAll(String searchData) {
        log.info("开始查询所有定义空间,查询条件:" + searchData);
        ListResult result = new ListResult();
        StopWatch st = StopWatch.createStarted();
        List<DtDefineSpace> list = null;
        try {
            list = dtDefineSpaceMapper.findAll(searchData);
            buildListSuccess(result, list);
        } catch (Exception e) {
            log.error("查询所有定义空间异常", e);
            buildListWarn(result, "查询所有定义空间失败");
        } finally {
            st.stop();
            log.info("本次分页查询耗时:" + st.getTime() + "ms");
        }
        return result;
    }

    /**
     * 根据医院soid模糊查询当前医院下员工信息
     *
     * @param orgInfoSoid
     * @param orgInfoType
     * @param search
     * @return
     */
    @Override
    public ListResult<List<DtDefineSpaceConsumerVo>> findListByOrgSoid(Long orgInfoSoid, Long orgInfoType, String search) {
        log.info("查询条件:1." + orgInfoSoid + "2." + search);
        ListResult result = new ListResult();
        StopWatch st = StopWatch.createStarted();
        List<DtDefineSpaceConsumerVo> list = null;
        DtDefineSpaceConsumerVo dtDefineSpaceConsumerVo = null;
//        try {
//            ListResult<List<EmployeeInfoVo>> listTmp =
//                    iEmployeeInfoApi.findListByOrgSoid(orgInfoSoid, orgInfoType, search);
//            if (listTmp != null && listTmp.getData() != null
//                    && listTmp.getData().size() > 0  ) {
//                List<EmployeeInfoVo> listEmployeeInfoVo = listTmp.getData();
//                list = new ArrayList<DtDefineSpaceConsumerVo>();
//                for (EmployeeInfoVo vo :listEmployeeInfoVo) {
//                    String doctorName  = vo.getEmployeeName();
//                    ListResult<List<BusinessUnitVo>> unitList =
//                            iBusinessUnitApi.findBusinessUnitListByEmployeeSoid(vo.getEmployeeSoid(),null);
//                    StringBuffer doctorNameWithUnitName = new StringBuffer(doctorName + "|");
//                    List<BusinessUnitVo> data = unitList.getData();
//                    for (int i = 0; i < data.size(); i++) {
//                        if(i == data.size() - 1){
//                            doctorNameWithUnitName.append(data.get(i).getBusinessUnitName());
//                        }else {
//                            doctorNameWithUnitName.append(data.get(i).getBusinessUnitName() + ",");
//                        }
//                    }
//                    dtDefineSpaceConsumerVo = new DtDefineSpaceConsumerVo();
//                    dtDefineSpaceConsumerVo.setDoctorNameWithUnitName(doctorNameWithUnitName.toString());
//                    dtDefineSpaceConsumerVo.setDoctorSoid(vo.getEmployeeSoid());
//                    list.add(dtDefineSpaceConsumerVo);
//                }
//
//            }
//            buildListSuccess(result, list);
//        } catch (Exception e) {
//            log.error("根据医院soid模糊查询当前医院下员工信息异常"+ e.getMessage(), e);
//            buildListWarn(result, "根据医院soid模糊查询当前医院下员工信息失败");
//        } finally {
//            st.stop();
//            log.info("本次分页查询耗时:" + st.getTime() + "ms");
//        }
        return result;

    }

    @Override
    public List<DtDefineSpaceConsumerVo> getDtDefineSpaceVos(Long defineSpaceSoid) {
        ListResult<DtDefineSpaceVo> lr = new ListResult<DtDefineSpaceVo>();
        //获取定义空间
        List<DtDefineSpaceConsumerVo> dtDefineSpaceConsumerVos = null;
        try {
            dtDefineSpaceConsumerVos = dtDefineSpaceConsumerMapper.getDefineSpaceSoid(defineSpaceSoid);
            buildListSuccess(lr, dtDefineSpaceConsumerVos);
        } catch (Exception e) {
            buildListWarn(lr,e);
        }
        return dtDefineSpaceConsumerVos;
    }

    /**
     * 添加定义空间用户数据
     *
     * @param dtDefineSpaceVo 目标定义空间
     * @param dtDefineSpace   源定义空间
     */
    private void insertDefineSpaceCounsumer(DtDefineSpaceVo dtDefineSpaceVo, DtDefineSpace dtDefineSpace) {
        List<DtDefineSpaceConsumerVo> dtDefineSpaceConsumerList = dtDefineSpaceVo.getDtDefineSpaceConsumerList();
        if (dtDefineSpaceConsumerList.size() != 0) {
            for (int i = 0; i < dtDefineSpaceConsumerList.size(); i++) {
                DtDefineSpaceConsumer dtDefineSpaceConsumer = new DtDefineSpaceConsumer();
//                dtDefineSpaceConsumer.setDefSpaceConsumerSoid(oIDGanerator.getSOID());
                dtDefineSpaceConsumer.setDefSpaceConsumerSoid(soidService.getSoid());
                dtDefineSpaceConsumer.setDefineSpaceSoid(dtDefineSpace.getDefineSpaceSoid());
                dtDefineSpaceConsumer.setDoctorSoid(dtDefineSpaceConsumerList.get(i).getDoctorSoid());
                dtDefineSpaceConsumer.setCreateDate(new Date());
                dtDefineSpaceConsumer.setIsDelete(0L);
                dtDefineSpaceConsumer.setStatus(dtDefineSpace.getStatus());
                dtDefineSpaceConsumerMapper.insert(dtDefineSpaceConsumer);
            }
        }
    }
}
